package com.flyduck.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flyduck.common.lang.Result;
import com.flyduck.service.SysRoleService;
import com.flyduck.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author flyduck
 * @since 2024-05-27
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends BaseController {

    @Autowired
    private SysRoleService sysRoleService;

    @PreAuthorize("hasAuthority('sys:role:list')")
    @GetMapping("/info/{id}")
    public Result<SysRoleDetailsRespVO> info(@PathVariable(name = "id") Long id){
        SysRoleDetailsRespVO sysRoleDetailsRespVO = sysRoleService.getRoleDetailsById(id);
        return Result.success(sysRoleDetailsRespVO);
    }

    @PreAuthorize("hasAuthority('sys:role:list')")
    @GetMapping("/list")
    public Result<Page<SysRoleRespVO>> getRolePageBySysRoleQueryReqVO(SysRoleQueryReqVO sysRoleQueryReqVO){
        Page page = getPage();
        Page<SysRoleRespVO> sysRoleRespVOPage = sysRoleService.getRolePageBySysRoleQueryReqVO(page,sysRoleQueryReqVO);
        return Result.success(sysRoleRespVOPage);
    }

    @PreAuthorize("hasAuthority('sys:role:save')")
    @PostMapping("/save")
    public Result<Void> saveRole(@Validated @RequestBody SysRoleSaveReqVO sysRoleSaveReqVO){
        sysRoleService.saveRole(sysRoleSaveReqVO);
        return Result.success();
    }

    @PreAuthorize("hasAuthority('sys:role:update')")
    @PostMapping("/update")
    public Result<Void> updateRole(@Validated @RequestBody SysRoleUpdateReqVO sysRoleUpdateReqVO){
        sysRoleService.updateRole(sysRoleUpdateReqVO);
        return Result.success();
    }

    @PreAuthorize("hasAuthority('sys:role:delete')")
    @PostMapping("/delete")
    public Result<Void> deleteByIds(@RequestBody Long[] ids){
        sysRoleService.deleteByIds(Arrays.asList(ids));
        return Result.success();
    }

    @PreAuthorize("hasAuthority('sys:role:perm')")
    @PostMapping("/perm/{roleId}")
    public Result<Void> assignMenusToRole(@PathVariable(name = "roleId")Long roleId,@RequestBody Long[] menuIds){
        sysRoleService.assignMenuListToRole(roleId,Arrays.asList(menuIds));
        return Result.success();
    }

}
